package top.itpath.admin.controller;

import cn.hutool.core.util.RandomUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import top.itpath.admin.dto.PasswordInfo;
import top.itpath.admin.entity.SysUser;
import top.itpath.admin.service.ISysUserRoleService;
import top.itpath.admin.service.IUserService;
import top.itpath.common.Result;
import top.itpath.common.event.UpdateUserRoleEvent;
import top.itpath.common.util.PasswordUtil;

import java.util.List;

/**
 * 系统/用户
 *
 * @author zhaomengru
 * create by  2023/10/10 - 14:19
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {

    private final IUserService userService;
    private final ISysUserRoleService userRoleService;

    private final ApplicationEventPublisher publisher;

    /**
     * 注册用户
     *
     * @param user 用户基本信息
     */
    @PostMapping("/add")
    Result<?> register(@RequestBody SysUser user) {
        return Result.success(userService.register(user));
    }

    /**
     * 更新用户密码
     *
     * @param passwordInfo 密码信息
     */
    @PostMapping("/update/password")
    Result<?> update(@RequestBody PasswordInfo passwordInfo) {
        SysUser byUsername = userService.findByUsername(passwordInfo.getUsername());
        if (!PasswordUtil.verify(passwordInfo.getOldPassword(), byUsername.getSalt(), byUsername.getPassword())) {
            return Result.fail("原密码错误");
        }
        String salt = RandomUtil.randomString(10);
        byUsername.setPassword(PasswordUtil.encrypt(passwordInfo.getNewPassword(), salt));
        byUsername.setSalt(salt);
        userService.updateById(byUsername);
        return Result.success();
    }

    /**
     * 设置用户角色
     */
    @PostMapping("/setRole")
    Result<?> setRole(@RequestParam Long userId,
                      @RequestBody Long[] roleIds) {
        SysUser user = userService.getById(userId);
        Assert.notNull(user, "用户不存在");
        userRoleService.setRole(userId, List.of(roleIds));
        publisher.publishEvent(new UpdateUserRoleEvent(this, user));
        return Result.success();
    }
}
